﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace tester
{
    public partial class Navigator : UserControl
    {
        public Navigator()
        {
            InitializeComponent();
        }

        private int mDelayAfterNavigation = 5;
        public  int DelayBeforeNavigation
        {
            get
            {
                return mDelayAfterNavigation;
            }
            set
            {
                mDelayAfterNavigation = value;
            }
        }
        
        public void GoTo(string url)
        {
            Delay(DelayBeforeNavigation * 1000);
            browser.Navigate(url);
            while (DocBusy) Application.DoEvents();
        }

        public void Delay(int msec) 
        {
            timer1.Interval = msec;
            timerTicked = false;
            timer1.Start();
            while (!timerTicked) Application.DoEvents();
            timer1.Stop();
        }

        private bool DocBusy = false;

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (DocBusy) 
            {
                DocBusy = false;
                return;
            }
        }

        private bool timerTicked = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            timerTicked = true;
        }

        private Object[] FromStringToObjArray(string opts) 
        {
            Object[] oParam = new Object[opts.Split(',').Count()];
            int i = 0;
            foreach (string val in opts.Split(','))
            {
                oParam[i] = (Object)val;
                i++;
            }
            return oParam;
        }

        public void ExecScript(string cmd, string opts) 
        {
            browser.Document.InvokeScript(cmd, FromStringToObjArray(opts));
        }

        public void ExecScript(string cmd) 
        {
            browser.Document.InvokeScript(cmd);
        }

        public void SubmitForm(string name, string data) 
        {
            browser.Document.Forms[name].InvokeMember("submit", FromStringToObjArray(data));
            
        }
        
    }
}
